<template>
  <div class="app-container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" style="margin-top: 2%">
      <el-form-item label="菜单名称">
        <el-input v-model="formInline.menuName" placeholder="菜单名称"></el-input>
      </el-form-item>

      <el-form-item style="margin-right: auto">
        <el-button type="primary" @click="onSubmit" size="small" icon="el-icon-search" v-hasPermi="['sys:menu:search']">搜索</el-button>
        <el-button type="primary" @click="addMenu" size="small" icon="el-icon-plus" v-hasPermi="['sys:menu:add']">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      :data="menus"
      row-key="menuId"
      border
      :default-expand-all=false
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
        prop="menuName"
        label="菜单名称"
        sortable
        width="180">
      </el-table-column>
      <el-table-column
        prop="path"
        label="路由地址"
        :show-overflow-tooltip="true"
        width="180">
      </el-table-column>
      <el-table-column
        prop="component"
        label="组件名称"
        :show-overflow-tooltip="true"
        width="180">
      </el-table-column>
      <!--<el-table-column
        prop="meta.icon"
        label="图标"
        width="180">
        <template slot-scope="scope">
          &lt;!&ndash;<div>{{scope.row.meta.icon}}</div>&ndash;&gt;
          <i :class="scope.row.meta.icon"></i>
        </template>
      </el-table-column>-->
      <el-table-column prop="meta.icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            v-if="scope.row.menuType!=='B'"
            v-hasPermi="['sys:menu:addinline']"
            @click="handleAdd(scope.$index, scope.row)">新增
          </el-button>
          <el-button
            size="mini"
            type="warning"
            plain
            v-hasPermi="['sys:menu:edit']"
            @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            plain
            v-if="showDel"
            v-hasPermi="['sys:menu:delete']"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--添加菜单-->
    <el-dialog
      title="添加菜单"
      :visible.sync="dialogVisible"
      width="500px" append-to-body
      :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                :options="options"
                :disable-branch-nodes="false"
                :show-count="true"
                :normalizer="normalizer"
                :value="tree.id"
                @select="getSelectInfo"
                :value-consists-of="valueConsistsOf"
                placeholder="请选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">菜单</el-radio>
                <el-radio label="B">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input
                placeholder="请输入菜单名称"
                v-model="form.menuName"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType!=='B'">
            <el-form-item label="路由地址" prop="path">
              <el-input
                placeholder="请输入路由地址"
                v-model="form.path"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--<el-form-item label="菜单图标">
              <el-input
                placeholder="请输入菜单图标"
                v-model="form.icon"
                clearable>
              </el-input>
            </el-form-item>-->
            <el-form-item v-if="form.menuType!=='B'" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                  <svg-icon
                    v-if="form.icon"
                    slot="prefix"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px;width: 16px;"
                  />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" @change="handleChange" :min="1" size="mini"></el-input-number>
            </el-form-item>
          </el-col>
          <!--<el-col :span="12" v-if="form.menuType!=='B'">
            <el-form-item label="是否外链" prop="isFrame">
              <el-select v-model="form.isFrame" clearable placeholder="请选择">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="12" v-if="form.menuType!=='B'">
            <el-form-item label="组件路径" prop="component">
              <el-input
                placeholder="组件路径"
                v-model="form.component"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input
                placeholder="权限标识"
                v-model="form.perms"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" >
            <el-form-item label="是否显示" prop="visible">
              <el-select v-model="form.visible" clearable placeholder="请选择">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.remark"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="subMenu">确 定</el-button>
            </span>
    </el-dialog>
    <!--添加表格菜单-->
    <el-dialog
      title="添加菜单"
      :visible.sync="open"
      width="500px" append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                :options="options"
                :disable-branch-nodes="false"
                :show-count="true"
                :normalizer="normalizer"
                :value="tree.id"
                :disabled="disabled"
                :value-consists-of="valueConsistsOf"
                placeholder="请选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">菜单</el-radio>
                <el-radio label="B">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input
                placeholder="请输入菜单名称"
                v-model="form.menuName"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType!=='B'">
            <el-form-item label="路由地址" prop="path">
              <el-input
                placeholder="请输入路由地址"
                v-model="form.path"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType!=='B'">
           <!-- <el-form-item label="菜单图标">
              <el-input
                placeholder="请输入菜单图标"
                v-model="form.icon"
                clearable>
              </el-input>
            </el-form-item>-->
            <el-form-item v-if="form.menuType != 'F'" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                  <svg-icon
                    v-if="form.icon"
                    slot="prefix"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px;width: 16px;"
                  />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" @change="handleChange" :min="1" size="mini" ></el-input-number>
            </el-form-item>
          </el-col>
          <!--<el-col :span="12" v-if="form.menuType!=='B'">
            <el-form-item label="是否外链" prop="isFrame">
              <el-select v-model="form.isFrame" clearable placeholder="请选择">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="12" v-if="form.menuType!=='B'">
            <el-form-item label="组件路径" prop="component">
              <el-input
                placeholder="组件路径"
                v-model="form.component"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input
                placeholder="权限标识"
                v-model="form.perms"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="是否显示" prop="visible">
              <el-select v-model="form.visible" clearable placeholder="请选择">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="form.remark"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="open = false">取 消</el-button>
                <el-button type="primary" @click="subMenuAdd">确 定</el-button>
            </span>
    </el-dialog>
    <!--修改-->
    <el-dialog
    title="修改菜单"
    :visible.sync="edit"
    width="500px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="24" v-if="form.menuType!=='B'">
          <el-form-item label="上级菜单">
            <treeselect
              :options="options"
              :disable-branch-nodes="false"
              :show-count="true"
              :normalizer="normalizer"
              @select="getSelectInfo"
              :value="tree.id"
              :disabled="disabled"
              :value-consists-of="valueConsistsOf"
              placeholder="请选择上级菜单"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="菜单类型" prop="menuType">
            <el-radio-group v-model="form.menuType">
              <el-radio label="M" >菜单</el-radio>
              <el-radio label="B">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单名称" prop="menuName">
            <el-input
              placeholder="请输入菜单名称"
              v-model="form.menuName"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.menuType!=='B'">
          <el-form-item label="路由地址" prop="path">
            <el-input
              placeholder="请输入路由地址"
              v-model="form.path"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.menuType!=='B'">
          <!-- <el-form-item label="菜单图标">
             <el-input
               placeholder="请输入菜单图标"
               v-model="form.icon"
               clearable>
             </el-input>
           </el-form-item>-->
          <el-form-item  label="菜单图标">
            <el-popover
              placement="bottom-start"
              width="460"
              trigger="click"
              @show="$refs['iconSelect'].reset()"
            >
              <IconSelect ref="iconSelect" @selected="selected" />
              <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                <svg-icon
                  v-if="form.icon"
                  slot="prefix"
                  :icon-class="form.icon"
                  class="el-input__icon"
                  style="height: 32px;width: 16px;"
                />
                <i v-else slot="prefix" class="el-icon-search el-input__icon" />
              </el-input>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.menuType!=='B'">
          <el-form-item label="组件路径" prop="component">
            <el-input
              placeholder="组件路径"
              v-model="form.component"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权限标识">
            <el-input
              placeholder="权限标识"
              v-model="form.perms"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input-number v-model="form.orderNum" controls-position="right" @change="handleChange" :min="1" size="mini"></el-input-number>
          </el-form-item>
        </el-col>
       <!-- <el-col :span="12" v-if="form.menuType!=='B'">
          <el-form-item label="是否外链" prop="isFrame">
            <el-select v-model="form.isFrame" clearable placeholder="请选择">
              <el-option label="是" value="0"></el-option>
              <el-option label="否" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>-->

        <el-col :span="12" >
          <el-form-item label="是否显示" prop="visible">
            <el-select v-model="form.visible" clearable placeholder="请选择">
              <el-option label="是" value="0"></el-option>
              <el-option label="否" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="form.remark"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
                <el-button @click="edit = false">取 消</el-button>
                <el-button type="primary" @click="subEditMenu">确 定</el-button>
            </span>
  </el-dialog>
  </div>
</template>

<script>
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import {getMenus,search,getTree,addMenu,getMenuByMenuId,deleteMenuAdmin,updateMenu} from '@/api/menu/menu'
  import IconSelect from "@/components/IconSelect";
  export default {
    components: {Treeselect,IconSelect},
    inject: ['reload'],
    data() {
      return {
        /**
         * 搜索菜单使用
         */
        formInline: {
          menuName: ''
        },
        showDel:true,
        /**
         * 对话框标识
         */
        dialogVisible: false,
        open: false,
        edit: false,
        /**
         * 表单信息
         */
        form: {
          menuId: '',
          menuName: '',
          parentId: 0,
          orderNum: '',
          path: '',
          component: '',
          isFrame: '',
          menuType: 'M',
          visible: '',
          status: "",
          perms:'',
          icon:'',
          remark:'',
          children:[]
        },
        /**
         * vueTreeSelect遍历使用的数组
         */
        options: [],
        //菜单树回显
        tree: {
          id: null,
          label: null
        },
        //菜单树是否可选
        disabled: false,
        /*radio: '1',*/
        /**
         * 遍历菜单数据表格
         */
        menus: [],
        /**
         * vueTreeSelect属性
         */
        valueConsistsOf: 'LEAF_PRIORITY',
        // 遮罩层
        loading: true,
        /**
         * 去掉children为空的数组
         * @param node
         * @returns {{children: *, id: *, label: *}}
         */
        normalizer(node) {
          if(node.children==null||node.children==='null'){
            delete node.children;
          }
        },
        rules: {
          menuName: [
            {required: true, message: "菜单名称不能为空", trigger: "blur"}
          ],
          menuType: [
            {required: true, message: "菜单类型不能为空", trigger: "blur"}
          ],
          /*component: [
            {required: true, message: "组件路径不能为空", trigger: "blur"}
          ],*/
          orderNum: [
            {required: true, message: "显示顺序不能为空", trigger: "blur"}
          ],
          path: [
            {required: true, message: "路由地址不能为空", trigger: "blur"}
          ],
          isFrame: [
            {required: true, message: "是否外链不能为空", trigger: "blur"}
          ],
          visible: [
            {required: true, message: "是否显示不能为空", trigger: "blur"}
          ],
        }

      }
    },
    created() {
      this.getMenu();
    },
    methods: {
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      handleChange(value) {
        console.log(value);
      },
      handleEdit(index, row) {
        this.edit = true;
        this.disabled = true;
        this.tree.label = row.menuName;
        this.tree.id = row.menuId;
        this.getSelectTree();
        getMenuByMenuId(row.menuId).then(res => {
          if (res.code === 200) {
            this.form = res.data;
          }
        });

        /* console.log(index, row);*/
      },
      handleAdd(index, row) {
        Object.keys(this.form).forEach(key => (this.form[key] = ""));
        this.open = true;
        this.disabled = true;
        this.tree.label = row.menuName;
        this.tree.id = row.menuId;
        this.getSelectTree();
      },
      handleDelete(index, row) {
        console.log(row);
        if(row.children!=null && row.children.length > 0 ) {
          this.$confirm('该菜单有子菜单,是否确认删除名称为"' + row.menuName + '"的数据项?', "警告", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteMenuAdmin(row).then(res=>{
              if (res.code===200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.reload();
                /*   this.$router.push("/index");*/
                console.log(res);
              }

            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }else {
          this.$confirm('是否确认删除名称为"' + row.menuName + '"的数据项?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            console.log(row);
            deleteMenuAdmin(row).then(res=>{
              if (res.code===200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.reload();
                /*   this.$router.push("/index");*/
                console.log(res);
              }

            })

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }
      },
      onSubmit() {
        let menuName = this.formInline.menuName;
        if (menuName == null || menuName==="" ) {
          this.showDel = true;
          this.getMenu();
        }else {
          search(menuName).then(res=>{
            if (res.code===200) {
              this.showDel = true;
              this.menus = res.data;
            }

          });
        }

      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      async getMenu() {
        this.loading = true;
        await getMenus().then(res => {
          if (res.code === 200) {
            this.loading = false;
            this.menus = res.data;
          }
        })
      },
      addMenu() {
        Object.keys(this.form).forEach(key => (this.form[key] = ""));
        this.tree.id = null;
        this.tree.label = null;
        this.dialogVisible = true;
        this.getSelectTree();
      },
      getSelectTree() {
        this.options = [];
        getTree().then(res => {
          this.options.push({id:0,label:'主菜单',children:res.data});
        })
      },
      getSelectInfo(node) {
        this.form.parentId = node.parentId;
        this.form.menuId = node.id
      },
      closeTree(value, instanceId) {
        console.log(value)
      },
      subMenu() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.dialogVisible = false;
            /*this.form.menuId = '';*/
            console.log(this.tree);
            console.log(this.form);
            addMenu(this.form).then(res => {
              console.log(this.form);
              if (res.code === 200) {
                this.msgSuccess("新增成功");
                this.reload();
              } else {
                this.msgError("新增失败");
              }
            });
          }
        })

      },

       subMenuAdd() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.open = false;
           /* console.log(this.tree);
            console.log(this.form);*/
              getMenuByMenuId(this.tree.id).then(res=>{
              console.log(res);
              if (res.code ===200) {
                //this.form.parentId = res.data.menuId;
               /* this.form.menuId = null;*/
                this.form.parentId = res.data.parentId;
                this.form.menuId = res.data.menuId;
                addMenu(this.form).then(res => {
                  console.log(this.form);
                  if (res.code === 200) {
                    this.msgSuccess("新增成功");
                    this.reload();
                  } else {
                    this.msgError("新增失败");
                  }
                });
              }
            })


          }
        })
      },
      subEditMenu() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.edit = false;
            console.log(this.tree);
            console.log(this.form);
            updateMenu(this.form).then(res=>{
              console.log(res);
              if (res.code===200) {
                this.msgSuccess("修改成功");
                this.reload();
              }
            });
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    display: flex;
    flex-direction: column;
  }
</style>
